﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuTouTiaoAssist.Util;

namespace QuTouTiaoAssist
{
    public partial class FrmDeviceCode : FrmOkCancelBase
    {
        public FrmDeviceCode()
        {
            InitializeComponent();
            base.ValidateRules.Add(this.textBox1, new ControlTextValidate(this.textBox1, OtherUtil.IsNullOrWhitespace, "设备号不能为空！", true, true));
        }

        private void FrmDeviceCode_Load(object sender, EventArgs e)
        {
            this.textBox1.Text = QttHelper.GetDeviceCode();
        }

        private void btnRefreshDeviceCode_Click(object sender, EventArgs e)
        {
            this.textBox1.Text = QttHelper.GenerateDeviceCode();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (!base.CheckValidateRule(this.textBox1))
                return;

            var code = this.textBox1.Text.Trim();
            QttHelper.SetDeviceCode(code);
            SaveDeviceCode(code);

            base.ReturnOk();
        }

        public static void SaveDeviceCode(string code)
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (!config.AppSettings.Settings.AllKeys.Contains("DeviceCode"))
                config.AppSettings.Settings.Add("DeviceCode", string.Empty);
            config.AppSettings.Settings["DeviceCode"].Value = code;
            config.Save();
        }
    }
}
